package com.foreveross.testproxy;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.constant.Constants;
import com.foreveross.model.ProxyIpModel;
import com.foreveross.testproxy.test.IPTestFactory;
import com.foreveross.testproxy.test.IPTester;
import com.foreveross.util.DateUtils;
import com.foreveross.util.ProxyIpUtil;
import com.foreveross.util.QueueUtil;
import com.foreveross.util.cfg.defaults.DefaultPropertiesLoader;
import com.foreveross.util.redis.JRedisImpl;
import com.foreveross.util.redis.RedisService;

public class ProxyIpTianxunProcess {
	private static Logger log = LoggerFactory
			.getLogger(ProxyIpTianxunProcess.class);

	public static boolean proxyIpTestProcess(String clientId) throws Exception {
		// 获取批量的IP
		List<ProxyIpModel> proxyList = ProxyIpUtil.getInstance()
				.downloadIps(1000);
		// 初始化 线程 100
		int processNum = Integer.parseInt(DefaultPropertiesLoader
				.getTianxunTestProcessThread());
		ExecutorService exeSvc = Executors.newCachedThreadPool();
		Queue tianxunQueue = QueueUtil.getTianxunQueue();	
		List<Future> fuidList = new ArrayList<Future>();

		IPTester ipTester = IPTestFactory.getInstance().getTianxunTester();

		RedisService redisService = new JRedisImpl();

		if (proxyList.size() < processNum) {

			for (int j = 0; j < 1000; j++) {
				log.info("不够IP继续获取IP数....." + proxyList.size());
				proxyList.addAll(ProxyIpUtil.getInstance().downloadIps(1000));
				log.info("不够IP继续获取IP数....." + proxyList.size());
				if (proxyList.size() >= processNum) {
					break;
				}
				Thread.sleep(1000);
			}

		}

		// 遍历执行
		if (proxyList.size() >= processNum) {

			for (int i = 0; i < processNum; i++) {
				log.error(proxyList.size() +":"+i);
				ProxyIpModel proxy = proxyList.get(i);
				proxyList.remove(proxy);
				Future future = exeSvc.submit(new ProxyTestTask(proxy, ipTester, redisService, clientId,tianxunQueue));
				fuidList.add(future);
			}

		}

		// 多线程执行
		for (Future fuid : fuidList) {
			try {
				String taskStatus = (String) fuid.get();
				//log.error("处理任务" + taskStatus);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		
		log.error("多线程结束关闭多线程");
		exeSvc.shutdown();
		
		return true;
	

	}

	public static class ProxyTestTask implements Callable<String> {
		private ProxyIpModel proxy;
		private IPTester ipTester;
		private RedisService redisService;
		private String clientId;
		private Queue tianxunQueue;

		public ProxyTestTask(ProxyIpModel proxy, IPTester ipTester,
				RedisService redisService, String clientId,Queue tianxunQueue) {
			this.proxy = proxy;
			this.ipTester = ipTester;
			this.redisService = redisService;
			this.clientId = clientId;
			this.tianxunQueue = tianxunQueue;

		}

		@Override
		public String call() throws Exception {
			long firsttime = System.currentTimeMillis();
			
			// 检测IP 往热池里写数据， 记录日志

			try {
				boolean flag = ipTester.test(proxy);
				if (flag) {
					log.info("成功放入队列");
					QueueUtil.putQueue(tianxunQueue, proxy);
					
					// 成功
//					boolean poolFlag = redisService.persistenceProxyIP(
//							Constants.CHANNEL_TIANXUN, proxy);
//					boolean logFlag = redisService.recordProxyIPLog(clientId,
//							Constants.CHANNEL_TIANXUN, 1, true);
//					log.info("成功入库" + poolFlag + " 日志：" + proxy.getIp());
				} else {

					log.info("失败入库日志" + proxy.getIp());
//					redisService.recordProxyIPLog(clientId,
//							Constants.CHANNEL_TIANXUN, 1, false);
				}

			} catch (Exception e) {
				log.info("检测IP 往热池里写数据， 记录日志: " + e.getMessage());
//				redisService.recordProxyIPLog(clientId,
//						Constants.CHANNEL_TIANXUN, 1, false);
			}
			log.error("redis处理时间"+(System.currentTimeMillis()-firsttime));
			return proxy.getIp() + ":" + proxy.getPort() + "处理完毕";
		}

	}

}
